package com.babel.util.util;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * 静态文件路径处理
 * @author daijie
 * @date 2017年7月8日
 */
public class StaticFileUtil {

	/**
	 * 在文件路径前添加静态文件服务器地址
	 * @param url
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String formatFileArrayJson(String path, String url){
		List<String> list = new ArrayList<>();
		ObjectMapper mapper = new ObjectMapper();
		if(url != null && url.length() > 0){
			if(JSONType.getJSONType(url).equals(JSONType.JSON_TYPE_ARRAY)){//如果字符串是JSON数组
				try {
					list = mapper.readValue(url, List.class);
					for (int i = 0; i < list.size(); i++) {
						list.set(i, path + list.get(i));
					}
				} catch (Exception e) {
					return url;
				}
			}else if(url.contains(",")){//如果字符串中多个文件是以“,”号隔开
				String[] urls = url.split(",");
				for (String str : urls) {
					list.add(formatFileStringJson(path, str));
				}
			}else{//如果都不是应该只有一个文件路径
				list.add(formatFileStringJson(path, url));
			}
		}
		try {
			return mapper.writeValueAsString(list);
		} catch (JsonProcessingException e) {
			return url;
		}
	}
	
	public static String formatFileStringJson(String path, String url) {
		if (url != null && url.length() > 0 && !url.contains("http")) {
			if (path.endsWith("/") && !url.startsWith("/")) {
				return path + url;
			} else if (!path.endsWith("/") && url.startsWith("/")) {
				return path + url;
			} else if (!path.endsWith("/") && !url.startsWith("/")) {
				return path + "/" + url;
			} else if (path.endsWith("/") && url.startsWith("/")) {
				return path + url.substring(1, url.length());
			}
		} else if (url != null && url.length() > 0 && url.contains("http")) {
			return url;
		}
		return "";
	}
	
}
